package com.example.lt.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.lt.entity.dto.AssignRoleDTO;
import com.example.lt.entity.dto.AuthorityDTO;
import com.example.lt.entity.user.Role;
import com.example.lt.entity.user.RolePermission;
import com.example.lt.entity.user.Tree;
import com.example.lt.entity.user.UserRole;
import com.example.lt.mapper.user.RoleMapper;
import com.example.lt.service.user.PermissionService;
import com.example.lt.service.user.RolePermissionService;
import com.example.lt.service.user.RoleService;
import com.example.lt.service.user.UserRoleService;
import com.example.lt.util.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.TransactionAnnotationParser;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 小涛Tao
 * @Date: 2024/08/16/18:49
 * version 1.0 注释：
 **/
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final RolePermissionService rolePermissionService;

    private final PermissionService permissionService;

    private final UserRoleService userRoleService;

    /**
     * 获取权限，树形结构
     * @return
     */
    @Override
    public List<Tree> tree() {
        final List<Tree> trees = permissionService.list(null).stream().map(permission -> {
            Tree tree = new Tree();
            BeanUtils.copyProperties(permission, tree);
            tree.setTitle(permission.getName());
            tree.setSpread(true);
            return tree;
        }).collect(Collectors.toList());

        List<Tree> parent = trees.stream().filter(tree -> tree.getPId().compareTo(0L) == 0).collect(Collectors.toList());
        for (Tree tree : parent) {
            tree.setChildren(new ArrayList<>());
            tree.getChildren().add(findChildren(tree, trees));
        }

        return parent;
    }

    @Override
    @Transactional
    public Result gaveRole(AssignRoleDTO assignRoleDTO) {
        // 1、获取被分配角色的id
        Long uId = assignRoleDTO.getUId();
        try {
            // 2、删除用户旧的角色
            userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, uId));

            List<UserRole> userRoles = new ArrayList<>();
            for (Long id : assignRoleDTO.getRId()) {
                UserRole userRole = new UserRole();
                userRole.setUserId(uId);
                userRole.setRoleId(id);
                userRoles.add(userRole);
            }
            // 3、保存用户新的角色
            userRoleService.saveBatch(userRoles);
        } catch (Exception e) {
            // 因为这里用 try/catch 块捕获了异常，事务是感受不到异常的，所以需要手动的调用事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); // 手动调用事务回滚
            return Result.error().message("分配角色失败");
        }
        return Result.ok().message("分配角色成功");
    }

    @Override
    @Transactional
    public Result removeRole(String id) {
        try {
            // 1、删除角色权限表中的记录
            rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, id));
            // 2、删除角色表中的记录
            removeById(id);
            // 3、删除用户角色表中的记录
            userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId, id));
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error().message("删除失败");
        }
        return Result.ok().message("删除成功");
    }

    @Override
    @Transactional
    public Result gavePermission(AuthorityDTO authorityDTO) {
        try {
            rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, authorityDTO.getRid()));
            List<RolePermission> list = new ArrayList<>();
            Integer rid = authorityDTO.getRid();
            for (Integer pId : authorityDTO.getPid()) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(rid);
                rolePermission.setPermissionId(pId);
                list.add(rolePermission);
            }
            rolePermissionService.saveBatch(list);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error().message("分配权限失败");
        }
        return Result.ok().message("权限分配成功");
    }


    private Tree findChildren(Tree datum, List<Tree> trees) {
        datum.setChildren(new ArrayList<Tree>());
        for (Tree tree : trees) {
            if (tree.getPId().compareTo(datum.getId()) == 0) {
                datum.getChildren().add(findChildren(tree,trees));
            }
        }
        return datum;
    }

}
